﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using SMS.Entities.BaseClasses;
using SMS.Model;
using System.Windows.Media.Imaging;
using System.IO;
using SMS.Common.Silverlight;

namespace SMS.ViewModel.User
{
    public class ChangeProfilePictureViewModel : BaseNotify
    {
        AuthenticationModel _model;
        public ChangeProfilePictureViewModel()
        {
            _model = new AuthenticationModel();
            _model.OnUploadImageCompleted += new Action<int>(_model_OnUploadImageCompleted);
            ImageUpload = new DelegateCommand(Upload);
        }

        void _model_OnUploadImageCompleted(int obj)
        {
            if (obj > 0)
            {
                UserMessage = "Profile Picture Uploaded!!";
            }
            _model.OnUploadImageCompleted -= new Action<int>(_model_OnUploadImageCompleted);
        }
        private void Upload(object param)
        {
            UserMessage = "Profile Picture Uploading....";
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = false;
            dlg.Filter = "All files (*.*)|*.*|PNG Images (*.png)|*.png";

            bool? retval = dlg.ShowDialog();

            if (retval != null && retval == true)
            {
                UploadFile(dlg.File.Name, dlg.File.OpenRead());                
            }
            else
            {
                UserMessage = "No file selected...";
            }
        }

        private void UploadFile(string fileName, Stream data)
        {
            string host = Application.Current.Host.Source.AbsoluteUri;
            host = host.Remove(host.IndexOf("/ClientBin"));

            UriBuilder ub = new UriBuilder(host + "/Handler1.ashx");
            ub.Query = string.Format("filename={0}", fileName);
            WebClient c = new WebClient();
            c.OpenWriteCompleted += (sender, e) =>
            {
                PushData(data, e.Result);
                e.Result.Close();
                data.Close();
            };
            c.WriteStreamClosed += (sender, e) =>
            {
                _model.UploadImage(App.LoggedinUserName, fileName);
                LoadImage(fileName);
            };
            c.OpenWriteAsync(ub.Uri);
        }
        private void LoadImage(string fileName)
        {
            WebClient downloader = new WebClient();
            downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
            //downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged);

            string host = Application.Current.Host.Source.AbsoluteUri;
            host = host.Remove(host.IndexOf("/ClientBin"));

            fileName = host + "/Images/" + fileName;
            downloader.OpenReadAsync(new Uri(fileName, UriKind.Absolute));
        }
        void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            BitmapImage loadedImage = new BitmapImage();
            loadedImage.SetSource(e.Result);

            Image = loadedImage;
        }

        private void PushData(Stream input, Stream output)
        {
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }

        private BitmapImage _Image;

        public BitmapImage Image
        {
            get { return _Image; }
            set { _Image = value; OnPropertyChanged("Image"); }
        }

        public ICommand ImageUpload { get; set; }
    }
}
